/**
 * Created by ruiyuan on 15-9-21.
 */
var marketService = require('../services/marketService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var redisKey = require('../config/redisKey');
var moment = require('moment');

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   start   */
var userService = require('../services/userService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   end   */

/**
 * 集市banner
 * @param req
 * @param res
 */
exports.getMarketBanners = function (req, res) {
    var user = req.user;

    marketService.getMarketBannersService(user, function (err, result) {
        if (err) {
            logger.error('Failed to getMarketBanners...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7001));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7001));
        }
    })
};

/**
 * 热门搜索
 * @param req
 * @param res
 */
exports.getGoodsHotQueryTerms = function (req, res) {

    marketService.getGoodsHotQueryTermsService(function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsHotQueryTerms...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7002));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7002));
        }
    });
};

/**
 * 商品分类列表
 * @param req
 * @param res
 */
exports.getGoodsCategoryList = function (req, res) {
    var code = 7003;
    var itemType = 1;
    if (req.query && parseInt(req.query.itemType) > 0)
        itemType = parseInt(req.query.itemType);
    marketService.getGoodsCategoryListService(itemType, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsCategoryList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, code));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, code));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 新增二手商品
 * @param req
 * @param res
 */
exports.addNewGoods = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to addNewGoods - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to addNewGoods - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to addNewGoods - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to addNewGoods! - " + gagOrNot);

                var user = req.user;
                var input = req.body;

                marketService.addNewGoodsService(user, input, function (err, result) {
                    if (err) {
                        logger.error('Failed to addNewGoods...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7004));
                    } else {
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   start   */
                        if(result != null) {
                            toolUtil.putMessageBusinessMQ({
                                msgType: 'publish_free_goods',
                                goodsId: result._id
                            })
                        }
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   end   */

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(user._id), 'goods', 1);

                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   start   */
                        var currCommunityId = user.community._id;
                        // redis保存取得用户选择小区ID
                        redisClient.get(user._id + ":currCommunityId", function (errComm, replyComm) {
                            if (!errComm) currCommunityId = replyComm;
                            /*  宝宝树66小区二次改造    mod   chenf  20170822   start   */
                            /*toolUtil.changeUserStatistics(user._id, currCommunityId, 'goods', 1);*/ // 新
                            toolUtil.changeUserStatisticsNew(user._id, 'goods', 1); // 新
                            /*  宝宝树66小区二次改造    mod   chenf  20170822   end   */
                        });

                        // toolUtil.changeUserStatistics(user._id, user.community._id, 'goods', 1); // 旧
                        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170815   end   */

                        var message = "";
                        toolUtil.hessianInvokeAddScore(user._id, 25, null, function (value) {
                            if (value != null && value.currentValue != null) {
                                message = "发布成功";
                            } else {
                                message = "发布成功"
                            }
                            res.json(messageUtil.composeSucceededMessage(req, message, null, 7004));

                            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   start   */
                            if(result != null) {
                                toolUtil.putMessageGoodsSmart({msgType: 1, goodsId: result._id})
                            }
                            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170816   end   */
                        })
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * 二手商品列表
 * @param req
 * @param res
 */
exports.getGoodsList = function (req, res) {
    logger.debug('market-controller getGoodsList start...');
    var user = req.user;
    var query = req.query;
    var ts = req.params.ts;

    marketService.getGoodsListService(user, ts, query, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7005));
        } else {
            var endTime = moment().endOf("week").add(-6, 'hour').toDate().getTime();
            result.list.forEach(function (temp) {
                if (temp.dealStatus != 1 && temp.saleNumber != null && new Date().getTime() < endTime) {
                    temp._doc['saleFlag'] = false
                } else {
                    temp._doc['saleFlag'] = true
                }
            });

            marketService.getGoodsItemRecord(user._id, result, function (err, data) {
                res.json(messageUtil.composeSucceededMessage(req, null, data, 7005));
            });
        }
    })
};

/**
 * 我收藏的二手
 * @param req
 * @param res
 */
exports.getFollowGoodsList = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;

    marketService.getFollowGoodsListService(user, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getFollowGoodsList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7006));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7006));
        }
    });
};

exports.getGoodsDetail = function (req, res) {
    var user = req.user;
    var goodsId = req.params.goodsId;
    var width = req.params.width;
    var query = req.query;

    marketService.getGoodsDetail(user, query, goodsId, width, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsDetail...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7007));
        } else {
            result._doc['userId'] = user._id;
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7007));

            if (query.clickSource != null && query.clickSource != '') {
                var message = {
                    userId: user._id,
                    contentId: goodsId,
                    type: 6,
                    clickSource: Number(query.clickSource),
                    typeDesc: '二手详情',
                    deviceId: req.params.deviceId,
                    createTime: new Date().getTime()
                };

                toolUtil.putMessageLogMQ(message);
            }
        }
    });
};

exports.getGoodsDetailForApp = function (req, res) {
    var user = req.user;
    var goodsId = req.params.goodsId;
    var query = req.query;

    marketService.getGoodsDetailForApp(user, query, goodsId, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsDetail...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7008));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7008));
        }
    });
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.addReply = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to addReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to addReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to addReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to addReply! - " + gagOrNot);

                var user = req.user;
                var input = req.cparams;

                marketService.addReply(user, input, function (err, result) {
                    if (err) {
                        logger.error('Failed to addReply...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7009));
                    } else {
                        //logger.info(result);

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(user._id), 'goodsReply', 1);
                        toolUtil.changeUserStatistics(user._id, user.community, 'goodsReply', 1);

                        var toReplyUid = result.replyTo == null ? "" : result.replyTo._id;
                        var replyTo = "";
                        var isAsk = 1;
                        if (toReplyUid == null || toReplyUid == "") {
                            isAsk = 0;
                        } else {
                            replyTo = toReplyUid;
                        }

                        var message = "";
                        toolUtil.hessianInvokeAddScore(user._id, 26, null, function (value) {
                            //if (value != null && value.currentValue != null && value.currentValue != 0) {
                            //    message = "回复成功，已获得" + value.changeValue + "积分";
                            //} else {
                            message = "回复成功";
                            //}
                            res.json(messageUtil.composeSucceededMessage(req, message, result, 7009));
                        });

                        toolUtil.putMessageBusinessMQ({
                            msgType: 'replyGoods',
                            goodsId: input.goodsId,
                            replyId: result._id,
                            toReplyUid: replyTo,
                            isAsk: isAsk
                        })
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getMyGoods = function (req, res) {
    var user = req.user;
    var ts = req.params.ts;
    var query = req.query;

    marketService.getMyGoods(user, ts, query, function (err, result) {
        if (err) {
            logger.error('Failed to getMyGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7010));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7010));
        }
    });
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.updateReleaseDate = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to updateReleaseDate - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to updateReleaseDate- " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to updateReleaseDate - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to updateReleaseDate! - " + gagOrNot);

                var goodsId = req.params.goodsId;
                var user = req.user;

                marketService.updateReleaseDate(goodsId, user, function (err) {
                    if (err) {
                        logger.error('Failed to updateReleaseDate...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7011));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 7011));

                        toolUtil.putMessageGoodsSmart({msgType: 1, goodsId: goodsId})
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.queryDeal = function (req, res) {
    var goodsId = req.params.goodsId;
    var token = req.params.token;

    marketService.queryDeal(goodsId, function (err) {
        if (err) {
            logger.error('Failed to queryDeal...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7012));
        } else {
            toolUtil.hessianInvokeAddScore(token, 27, null, function (value) {
            });
            res.json(messageUtil.composeSucceededMessage(req, null, null, 7012));
        }
    });
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.delGoods = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to delGoods - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to delGoods - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to delGoods - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to delGoods! - " + gagOrNot);

                var goodsId = req.params.goodsId;
                var token = req.params.token;

                marketService.delGoods(goodsId, function (err, result) {
                    if (err) {
                        logger.error('Failed to delGoods...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7013));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 7013));

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'goods', -1);
                        /*  宝宝树66小区二次改造    mod   chenf  20170822   start   个人页数据统计修改*/
                        /*toolUtil.changeUserStatistics(token, result.community, 'goods', -1);*/
                        toolUtil.changeUserStatisticsNew(token,'goods', -1);
                        /*  宝宝树66小区二次改造    mod   chenf  20170822   end   个人页数据统计修改*/

                        toolUtil.hessianInvokeAddScore(token, 30, null, function (value) {
                        });
                        toolUtil.putMessageGoodsSmart({msgType: 2, goodsId: goodsId, category: result.category})

                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.backdelGoods = function (req, res) {
    // 由于opm-v2也要调取这个接口，禁言功能暂时取消
    /*var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to backdelGoods - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to backdelGoods - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to backdelGoods - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to backdelGoods! - " + gagOrNot);
                var goodsId = req.params.goodsId;
                marketService.delGoods(goodsId, function (err, result) {
                    if (err) {
                        logger.error('Failed to delGoods...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 3000));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 3000));

                        //统计用户数据
                        var userId = result.createdBy;
                        toolUtil.changeUserStatistics(userId, result.community, 'goods', -1);
                        toolUtil.hessianInvokeAddScore(userId, 30, null, function (value) {});
                    }
                });
            }
        }
    });*/
    var goodsId = req.params.goodsId;
    marketService.delGoods(goodsId, function (err, result) {
        if (err) {
            logger.error('Failed to delGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 3000));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 3000));

            //统计用户数据
            var userId = result.createdBy;
            /*  宝宝树66小区二次改造    mod   chenf  20170822   start   个人页数据统计修改*/
            /*toolUtil.changeUserStatistics(userId, result.community, 'goods', -1);*/
            toolUtil.changeUserStatisticsNew(userId, 'goods', -1);
            /*  宝宝树66小区二次改造    mod   chenf  20170822   end   个人页数据统计修改*/
            toolUtil.hessianInvokeAddScore(userId, 30, null, function (value) {});
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.delGoodsReply = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to delGoodsReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to delGoodsReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to delGoodsReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to delGoodsReply! - " + gagOrNot);

                var replyId = req.params.replyId;
                var goodsId = req.params.goodsId;

                marketService.delGoodsReply(replyId, function (err) {
                    if (err) {
                        logger.error('Failed to delGoodsReply...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7014));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 7014));

                        var key = "goods:" + goodsId + ":detail";
                        //统计用户数据
                        redisClient.HINCRBY(key, 'replyCount', -1);

                        toolUtil.hessianInvokeAddScore(token, 31, null, function (value) {
                        })
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getOtherGoods = function (req, res) {
    var user = req.params.user;
    var ts = req.params.ts;
    var query = req.query;

    marketService.getOtherGoods(user, ts, query, function (err, result) {
        if (err) {
            logger.error('Failed to getOtherGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7015));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7015));
        }
    });
};

exports.getRepliesByGoodsId = function (req, res) {
    var goodsId = req.params.goodsId;
    var ts = req.cparams.ts;

    marketService.getRepliesByGoodsId(goodsId, ts, function (err, result) {
        if (err) {
            logger.error('Failed to getRepliesByGoodsId...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7016));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7016));
        }
    });
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.updateGoods = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to updateGoods - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to updateGoods - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to updateGoods - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to updateGoods! - " + gagOrNot);

                var user = req.user;
                var input = req.body;
                var goodsId = req.params.goodsId;

                marketService.updateGoodsService(goodsId, input, function (err, result) {
                    if (err) {
                        logger.error('Failed to updateGoodsService...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7017));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, '编辑成功', result, 7017));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.getRecGoodsList = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to getRecGoodsList - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to getRecGoodsList - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to getRecGoodsList - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to getRecGoodsList! - " + gagOrNot);


                var user = req.user;
                var query = req.query;
                var ts = req.params.ts;

                marketService.getRecGoodsListService(user, ts, query, function (err, result) {
                    if (err) {
                        logger.error('Failed to getRecGoodsList...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7018));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result, 7018));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getSaleGoodsList = function (req, res) {
    var user = req.user;
    var query = req.query;
    var ts = req.params.ts;

    marketService.getSaleGoodsListService(user, ts, query, function (err, result) {
        if (err) {
            logger.error('Failed to getSaleGoodsList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7019));
        } else {

            var endTime = moment().startOf('week').add(6, 'day').add(22, 'hour');

            if (moment().isAfter(endTime)) {
                result.list = [];
            }

            res.json(messageUtil.composeSucceededMessage(req, null, result, 7019));
        }
    })
};

exports.getSaleNotifyMessage = function (req, res) {

    marketService.getSaleNotifyMessageService(function (err, result) {
        if (err) {
            logger.error('Failed to getSaleNotifyMessage ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7020))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(result), 7020));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.addSaleRecord = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to addSaleRecord - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to addSaleRecord - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to addSaleRecord - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to addSaleRecord! - " + gagOrNot);

                var user = req.user;
                var input = req.body;

                marketService.addSaleRecordService(user, input, function (err, result) {
                    if (err) {
                        logger.error('Failed to addSaleRecordService ---' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7020))
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 7020));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.sendMessage = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to sendMessage - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to sendMessage - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to sendMessage - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to sendMessage! - " + gagOrNot);

                var user = req.user;
                var input = req.body;

                marketService.sendMessageService(user, input, function (err, result) {
                    if (err) {
                        logger.error('Failed to sendMessage ---' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 7020))
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 7020));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.searchGoods = function (req, res) {
    var user = req.user;
    /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 start */
    var keyword = req.body.keyword;
    var goodsClaId = req.body.goodsClaId;
    var ts = req.body.ts;
    /* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171128 start */

    marketService.searchGoodsService(user, keyword, goodsClaId, ts, function (err, result) {
        if (err) {
            logger.error('Failed to searchGoods ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7020))
        } else {
            marketService.getGoodsItemRecord(user._id, result, function (err, data) {
                res.json(messageUtil.composeSucceededMessage(req, null, data, 7020));

                if (ts == '*') {
                    var message = {
                        userId: user._id,
                        type: 74,
                        typeDesc: '集市搜索（含关键字）',
                        ext: keyword,
                        deviceId: req.params.deviceId,
                        createTime: new Date().getTime()
                    };

                    toolUtil.putMessageLogMQ(message);
                }
            });
        }
    })
};

/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 start */
// 1120-commit-master
exports.searchGoodsCategoryList = function (req, res) {
    var code = 7003;
    var itemType = 1;
    if (req.query && parseInt(req.query.itemType) > 0)
        itemType = parseInt(req.query.itemType);
    marketService.searchGoodsCategoryListService(itemType, function (err, result) {
        if (err) {
            logger.error('Failed to getGoodsCategoryList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, code));
        } else {
            var data = [];
            if (result) {
                for (var i = 0, length = result.length; i < length; i++) {
                    var goodsCtgObj = {};
                    goodsCtgObj.goodsClaId = result[i].id;
                    goodsCtgObj.name = result[i].name;
                    data.push(goodsCtgObj);
                }
            }
            // var data = {
            //     list: list
            // };
            res.json(messageUtil.composeSucceededMessage(req, null, data, code));
        }
    })
};
/* 宝宝树66小区 sprint5 闲置搜索页 增加闲置分类搜索 add wangcan 20171115 end */

exports.publicGetMarketBanners = function (req, res) {
    marketService.publicGetMarketBannersService(function (err, result) {
        if (err) {
            logger.error('Failed to publicGetMarketBannersService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7001));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7001));
        }
    })
};

exports.publicGetGoodsList = function (req, res) {
    logger.debug('market-controller publicGetGoodsList start...');
    var query = req.query;
    var ts = req.params.ts;

    marketService.publicGetGoodsListService(ts, query, function (err, result) {
        if (err) {
            logger.error('Failed to publicGetGoodsListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7005));
        } else {
            var endTime = moment().endOf("week").add(-6, 'hour').toDate().getTime();
            result.list.forEach(function (temp) {
                if (temp.dealStatus != 1 && temp.saleNumber != null && new Date().getTime() < endTime) {
                    temp._doc['saleFlag'] = false
                } else {
                    temp._doc['saleFlag'] = true
                }
            });
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7005));
        }
    })
};

/* 宝宝树66小区 sprint5 66小区APP"我的"页面 新增我的拼团收藏功能 add wangcan 20171117 start */
// APP调用-我的拼团收藏
exports.getFightGroupsCollectList = function (req, res) {
    var query = req.query;
    // var ts = req.params.ts;
    var token = req.body.token;
    var ts = req.body.ts;
    var screenWidth = req.body.screenWidth;
    var screenHeight = req.body.screenHeight;

    logger.debug("美囤token:" + token);

    marketService.getFightGroupsCollectListService(ts, token, screenWidth, screenHeight, query, function (err, result) {
        if (err) {
            logger.error('Failed to publicGetGoodsListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
        } else {
            // var endTime = moment().endOf("week").add(-6, 'hour').toDate().getTime();
            // result.list.forEach(function (temp) {
            //     if (temp.dealStatus != 1 && temp.saleNumber != null && new Date().getTime() < endTime) {
            //         temp._doc['saleFlag'] = false
            //     } else {
            //         temp._doc['saleFlag'] = true
            //     }
            // });
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
        }
    })
};
/* 宝宝树66小区 sprint5 66小区APP"我的"页面 新增我的拼团收藏功能 add wangcan 20171117 end */

exports.publicGetGoodsDetail = function (req, res) {
    var goodsId = req.params.goodsId;
    var width = req.params.width;
    var query = req.query;

    marketService.publicGetGoodsDetailService(query, goodsId, width, function (err, result) {
        if (err) {
            logger.error('Failed to publicGetGoodsDetailService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7007));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7007));
        }
    });
};
